﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using wms.Common;

namespace wms.Pages
{
    /// <summary>
    /// RecordOutInput.xaml 的交互逻辑
    /// </summary>
    public partial class RecordOutInput : Window
    {
        private int? _id;
        private int? _state;
        private DataTable dt = null;

        public RecordOutInput(int? id = null)
        {
            this.Id = id;
            ChangeLanguage.changePage(Variable.LanguageSeesion.ToString());
            InitializeComponent();
        }

        bool IsMouseDown = false;
        Point mousePoint; //上一次鼠标在canvas上的位置
        object target = null; //被拖动的对象


        private void move_target_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                IsMouseDown = true;
                mousePoint = e.GetPosition(this.canvas);
                target = sender;
            }
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (IsMouseDown)
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    Point currentMousePoint = e.GetPosition(this.canvas); //当前鼠标在canvas上的位置
                    Canvas.SetLeft((UIElement)target, Canvas.GetLeft(((UIElement)target)) + (currentMousePoint.X - mousePoint.X));
                    Canvas.SetBottom((UIElement)target, Canvas.GetBottom(((UIElement)target)) + (mousePoint.Y - currentMousePoint.Y));
                    mousePoint = currentMousePoint;
                }
            }
        }

        private void Window_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (IsMouseDown)
            {
                IsMouseDown = false;
            }
        }

        private void cbx_scan_Checked(object sender, RoutedEventArgs e)
        {
            this.canvas.Visibility = Visibility.Visible;
        }

        private void cbx_scan_Unchecked(object sender, RoutedEventArgs e)
        {
            this.canvas.Visibility = Visibility.Hidden;
        }


        private void btn_select_Click(object sender, RoutedEventArgs e)
        {
            GoodsSelect gs = new GoodsSelect("出库");
            gs.ShowDialog();
            List<DataRow> list = gs.Result;
            if (gs.Result != null && gs.Result.Count > 0)
            {

                foreach (var item in gs.Result)
                {
                    DataRow row = item as DataRow;
                    string code = row["code"].ToString();

                    //先判断是否已经加入，如果是，直接加数量
                    DataRow view_row = Find(code);
                    if (view_row != null)
                    {
                        view_row["qty"] = Utils.ParseInt(view_row["qty"]) + 1;
                    }
                    else
                    {
                        //加入到列表
                        DataRow dr = dt.NewRow();
                        dr["goods_id"] = row["id"];
                        dr["name"] = row["name"];
                        dr["code"] = row["code"];
                        dr["client"] = row["client"];
                        dr["weight"] = row["weight"];
                        dr["qty"] = 1;
                        dr["memo"] = "";
                        dr["type"] = row["type"];
                        dr["size"] = row["size"];
                        dr["value"] = row["value"];
                        this.dt.Rows.Add(dr);
                    }
                }
            }
            calc();
        }


        //判断集合中是否包含指定code
        private DataRow Find(string code)
        {

            foreach (var item in dt.Rows)
            {
                DataRow row = item as DataRow;
                if (code.Equals(row["code"]))
                {
                    return row;
                }
            }
            return null;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //初始化出库类型下拉菜单
            string[] array = Property.Get("type.out").Split('\n');
            List<string> list = new List<string>();
            foreach (string s in array)
            {
                string str = s.Trim();
                if (!string.IsNullOrWhiteSpace(str))
                {
                    list.Add(str);
                }
            }
            this.txt_type.ItemsSource = list;
            //默认选中第一个出库类型
            this.txt_type.SelectedIndex = 0;

            this.dt = new DataTable();
            dt.Columns.Add("pqty");
            dt.Columns.AddRange(new DataColumn[] { new DataColumn("goods_id", typeof(int)), new DataColumn("name"), new DataColumn("code"), new DataColumn("client"), new DataColumn("weight"), new DataColumn("qty", typeof(int)), new DataColumn("memo"), new DataColumn("type"), new DataColumn("size"), new DataColumn("value") });
            this.dataGrid.ItemsSource = dt.DefaultView;
            //新增
            if (this.Id == null)
            {
                string code_number = DBHelper.GetDataSingle("select top 1 code_number from t_numbers where state = 0 and type = 1 order by id") as string;
                if (string.IsNullOrWhiteSpace(code_number))
                {
                    MessageBox.Show("系统单号已经用完，无法自动生成单号");
                }
                else
                {
                    DBHelper.ExcuteSQL("update t_numbers set state = 1 where code_number = @code_number", new SqlParameter[] { new SqlParameter("@code_number", code_number) });
                    this.txt_record_number.Text = code_number;
                }
                this.txt_create_time.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                this.txt_transactor.Text = Auth.Name;

            }
            //编辑
            else
            {

                Dictionary<string, object> dictionary = DBHelper.GetDataOne("select * from t_record_out where id = " + this.Id);
                this.txt_record_number.Text = Utils.Parse(dictionary["record_number"]);
                this.txt_create_time.Text = Utils.ParseDateTime(dictionary["create_time"], "yyyy-MM-dd HH:mm");
                this.txt_transactor.Text = Utils.Parse(dictionary["transactor"]);
                this.txt_type.Text = Utils.Parse(dictionary["type"]);
                this.txt_memo.Text = Utils.Parse(dictionary["memo"]);
                this.txt_describe.Text = Utils.Parse(dictionary["describe"]);
                this.State = Utils.ParseInt(dictionary["state"]);

                DataTable table = DBHelper.GetDataTable("select t.pre_quantity,t.id,t.record_out_id,t.goods_id,t.quantity,t.memo,t2.code,t2.name,t2.type,t2.size,t2.weight,t2.client,t2.value from t_record_out_item t inner join t_goods t2 on t.goods_id = t2.id where t.record_out_id = " + this.Id);
                if (table != null && table.Rows.Count > 0)
                {

                    foreach (DataRow row in table.Rows)
                    {
                        //加入到列表
                        DataRow dr = dt.NewRow();
                        dr["pqty"] = row["pre_quantity"];
                        if (string.IsNullOrWhiteSpace(dr["pqty"].ToString()))
                        {
                            dr["pqty"] = 0;
                        }
                        dr["goods_id"] = row["goods_id"];
                        dr["name"] = row["name"];
                        dr["code"] = row["code"];
                        dr["client"] = row["client"];
                        dr["weight"] = row["weight"];
                        dr["qty"] = row["quantity"];
                        dr["memo"] = row["memo"];
                        dr["type"] = row["type"];
                        dr["size"] = row["size"];
                        dr["value"] = row["value"];
                        this.dt.Rows.Add(dr);
                    }
                }
            }

            dataGrid_SelectionChanged(sender, null);
            calc();
        }

        private void txt_scan_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                string code = this.txt_scan.Text;
                if (string.IsNullOrWhiteSpace(code))
                {
                    return;
                }
                //判断该物品是否有库存
                string sqlnum = "select id,case when  dbo.f_goods_quantity(id)>0 THEN '1' ELSE '0' END as quntity from t_goods where code like '%' + @key + '%'";
                Dictionary<string, object> paramnum = new Dictionary<string, object>();
                paramnum.Add("@key", code);
                DataTable dtnum = DBHelper.GetDataTable(sqlnum, paramnum);
                if (dtnum.Rows.Count == 0)
                {
                    MessageBox.Show("SKU【"+code+"】，不存在!");
                    this.txt_scan.Text = "";
                    this.txt_scan.Focus();
                    return;
                }
                int quntity = int.Parse(dtnum.Rows[0]["quntity"].ToString());
                //库存大于0，可以出库；等于0不能出库
                if (quntity == 0)
                {
                    MessageBox.Show("物品编码【" + code + "】,库存不足，不能出库");
                    this.txt_scan.Text = "";
                    this.txt_scan.Focus();
                    return;
                }
                //先判断是否已经加入，如果是，直接加数量
                DataRow view_row = Find(code);
                if (view_row != null)
                {
                    view_row["qty"] = Utils.ParseInt(view_row["qty"]) + 1;
                    calc();
                    this.txt_scan.Text = "";
                    return;
                }

                Dictionary<string, object> param = new Dictionary<string, object>();
                string sql = "select * from t_goods where code = @code";
                param.Add("@code", code);

                DataTable table = DBHelper.GetDataTable(sql, param, "id");
                if (table.Rows.Count > 0)
                {
                    foreach (var item in table.Rows)
                    {
                        DataRow row = item as DataRow;

                        DataRow dr = dt.NewRow();
                        dr["pqty"] = 0;
                        dr["goods_id"] = row["id"];
                        dr["name"] = row["name"];
                        dr["code"] = row["code"];
                        dr["client"] = row["client"];
                        dr["weight"] = row["weight"];
                        dr["qty"] = 1;
                        dr["memo"] = "";
                        dr["type"] = row["type"];
                        dr["size"] = row["size"];
                        dr["value"] = row["value"];
                        this.dt.Rows.Add(dr);
                    }
                }
                else
                {
                    DataRow dr = dt.NewRow();
                    dr["pqty"] = 0;
                    dr["goods_id"] = DBNull.Value;
                    dr["name"] = null;
                    dr["code"] = code;
                    dr["client"] = null;
                    dr["weight"] = null;
                    dr["qty"] = 1;
                    dr["memo"] = "";
                    dr["type"] = null;
                    dr["size"] = null;
                    dr["value"] = null;
                    this.dt.Rows.Add(dr);
                }
                calc();
                this.txt_scan.Text = "";
            }
        }

        private void btn_save_Click(object sender, RoutedEventArgs e)
        {
            if (this.State == 2)
            {
                MessageBox.Show("已经审核，不能修改");
                return;
            }

            string record_number = this.txt_record_number.Text;
            DateTime? create_time = Utils.ParseDateTime(this.txt_create_time.Text);
            string transactor = this.txt_transactor.Text;
            string type = this.txt_type.Text;
            string memo = this.txt_memo.Text;
            string describe = this.txt_describe.Text;

            if (string.IsNullOrWhiteSpace(record_number))
            {
                MessageBox.Show("请填写有效的出库单号");
                return;
            }
            if (create_time == null)
            {
                MessageBox.Show("请填写有效的业务日期");
                return;
            }

            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("没有物品信息");
                return;
            }

            DataTable dt_new = new DataTable();
            dt_new.Columns.AddRange(new DataColumn[] { new DataColumn("name"), new DataColumn("qpty"), new DataColumn("code"), new DataColumn("weight"), new DataColumn("quantity"), new DataColumn("type"), new DataColumn("size"), new DataColumn("value"), new DataColumn("client") });

            foreach (var item in dt.Rows)
            {
                DataRow row = item as DataRow;
                if (row["goods_id"] == null || row["goods_id"] == DBNull.Value)
                {
                    DataRow dr_new = dt_new.NewRow();
                    dr_new["code"] = row["code"];
                    dt_new.Rows.Add(dr_new);
                }
            }

            if (dt_new.Rows.Count > 0)
            {
                if (MessageBox.Show("有" + dt_new.Rows.Count + "个物品不在当前系统中，是否保存这些物品？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    new GoodsImport(dt_new).ShowDialog();

                    //重新读取数据库，获取物品id
                    foreach (var item in dt.Rows)
                    {
                        DataRow row = item as DataRow;
                        if (row["goods_id"] == null || row["goods_id"] == DBNull.Value)
                        {
                            string code = row["code"].ToString();
                            Dictionary<string, object> data = DBHelper.GetDataOne("select * from t_goods where code = @code", new Dictionary<string, object> { { "@code", code } });
                            if (data != null)
                            {
                                row["goods_id"] = data["id"];
                                row["name"] = data["name"];
                                row["client"] = data["client"];
                                row["weight"] = data["weight"];
                                row["type"] = data["type"];
                                row["size"] = data["size"];
                                row["value"] = data["value"];
                            }
                        }
                    }
                    calc();
                }
                return;
            }

            try
            {

                //新增
                if (this.Id == null)
                {
                    this.Id = DBHelper.Insert("insert into t_record_out(record_number,transactor,create_time,memo,describe,type,state) values(@record_number,@transactor,@create_time,@memo,@describe,@type,@state)",
                       new Dictionary<string, object> {
                        { "@record_number", record_number },
                        { "@transactor", transactor },
                        { "@create_time", create_time },
                        { "@memo", memo },
                        { "@describe", describe },
                        { "@type", type },
                        { "@state", 1 }
                       });
                }
                //修改
                else
                {
                    int r = DBHelper.ExcuteSQL("update t_record_out set record_number = @record_number,transactor = @transactor,create_time = @create_time,memo = @memo,describe = @describe,type = @type, modify_time = getdate(), modify_user = @modify_user where state = 1 and id = @id",
                       new Dictionary<string, object> {
                        { "@record_number", record_number },
                        { "@transactor", transactor },
                        { "@create_time", create_time },
                        { "@memo", memo },
                        { "@describe", describe },
                        { "@type", type },
                        { "@id", this.Id }
                       });

                    if (r == 0)
                    {
                        MessageBox.Show("保存失败");
                        return;
                    }
                    DBHelper.ExcuteSQL("delete t_record_out_item where record_out_id = " + this.Id.ToString());
                }


                if (this.Id != null && this.dt.Rows.Count > 0)
                {
                    int count = 0;
                    foreach (DataRow row in this.dt.Rows)
                    {
                        int? item_goods_id = Utils.ParseInt(row["goods_id"]);
                        int? item_quantity = Utils.ParseInt(row["qty"]);
                        string item_memo = Utils.Parse(row["memo"]);
                        //保存

                        int r = DBHelper.ExcuteSQL("insert into t_record_out_item(record_out_id,goods_id,quantity,memo) values(@record_out_id,@goods_id,@quantity,@memo)",
                           new Dictionary<string, object> {
                            { "@record_out_id", this.Id },
                            { "@goods_id", item_goods_id },
                            { "@quantity", item_quantity },
                            { "@memo", item_memo }
                           });

                        count += r;
                    }
                    MessageBox.Show("保存成功，共保存" + count + "条明细");
                }
            }
            catch (SqlException se)
            {
                MessageBox.Show("保存失败\n" + se.Message);
            }
        }

        private void btn_delete_Click(object sender, RoutedEventArgs e)
        {
            IList list = this.dataGrid.SelectedItems as IList;
            if (list == null || list.Count == 0)
            {
                MessageBox.Show("没有选中任何记录");
                return;
            }
            List<DataRow> temp = new List<DataRow>();
            foreach (var item in list)
            {
                if (item is DataRowView)
                {
                    temp.Add((item as DataRowView).Row);
                }
            }
            foreach (var r in temp)
            {
                r.Delete();
            }
            calc();
        }

        private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            IList list = this.dataGrid.SelectedItems as IList;
            this.btn_delete.IsEnabled = (list == null || list.Count == 0) ? false : true;
        }


        private void calc()
        {
            int total_type = 0;
            int total_count = 0;
            float total_amount = 0;
            if (dt != null)
            {
                foreach (DataRow row in dt.Rows)
                {
                    int? qty = Utils.ParseInt(row["qty"]);
                    float? value = Utils.ParseFloat(row["value"]);
                    total_type++;
                    if (qty != null)
                    {
                        total_count += (int)qty;
                    }
                    if (value != null && qty != null)
                    {
                        total_amount += (float)(value * qty);
                    }
                }
            }
            this.txt_total_type.Text = total_type.ToString();
            this.txt_total_count.Text = total_count.ToString();
            this.txt_total_amont.Text = total_amount.ToString();
        }

        private void btn_close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btn_verify_Click(object sender, RoutedEventArgs e)
        {
            if (this.Id == null)
            {
                MessageBox.Show("请先执行保存");
                return;
            }

            if (this.State == 2)
            {
                MessageBox.Show("已经审核");
                return;
            }
            string message = "";
            DataView dts = (DataView)this.dataGrid.ItemsSource;
            DataTable list = dts.ToTable();
            for (int i = 0; i < list.Rows.Count; i++)
            {
                //if (list.Rows[i]["pqty"]!=list.Rows[i]["qty"])
                //{
                //    message += "审核失败，物品编码【" + list.Rows[i]["code"].ToString() + "】" + "申请出库数量:" + list.Rows[i]["pqty"].ToString() + "," + "扫描数量:" + list.Rows[i]["qty"].ToString() + "\r\n";
                //}
            }
            if (message != "")
            {
                MessageBox.Show(message);
            }
            else
            {
                int r = DBHelper.ExcuteSQL("update t_record_out set state = 2 where state = 1 and id = " + this.Id);
                if (r > 0)
                {
                    this.State = 2;
                    MessageBox.Show("审核成功");
                }
            }

            //DataTable dt = DBHelper.GetDataTable("select case when quantity = pre_quantity then 'true' else 'false' end as result from t_record_out_item where id= " + this.Id);
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    Dictionary<string, object> dic = new Dictionary<string, object>();
            //    string result = "";
            //    foreach (DataColumn column in dt.Columns)
            //    {
            //        var value = dt.Rows[0][column.ColumnName];
            //        result = value.ToString();
            //    }



            //}

        }

        public int? Id
        {
            get
            {
                return _id;
            }

            set
            {
                _id = value;
            }
        }

        public int? State
        {
            get
            {
                return _state;
            }

            set
            {
                _state = value;
            }
        }

        private void dataGrid_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
        {
            calc();
        }
    }
}
